const
    globalData = getApp().globalData,
    utils = require('../../utils/util'),
    base = require('../../api/base');

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        visible: {
            type: Boolean,
            value: true
        },

        width: {
            type: Number,
            value: 500
        },

        height: {
            type: Number,
            value: 666
        },

        type: {
            type: Number,
            value: 0, //0 医院    1 医生    2 spu   3 sku   4 AI测颜    5 超级会员
        },

        hideClose: {
            type: Boolean,
            value: false
        },

        className: {
            type: String,
            value: ''
        },

        data: {
            type: Object,
            value: {}
        }
    },

    observers: {
        visible(newV, old) {
            if (newV) {
                this.setData({ sheetVisible: true });
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        imageBaseUri: globalData.imageBaseUri,
        sheetVisible: true,
        canvasVisible: false,
        tempSrc: '',
        modalAuth: { //授权弹窗
            show: false,
            mask: false,
            content: '您是否愿意授权【TNTB】使用您的相册？',
        },
        toast: {
            visible: false,
            text: ''
        }
    },

    attached() {
        let sys = globalData.SystemInfo,
            dpr = sys.pixelRatio,
            { width, height } = this.data;

        this.canvasLoad = new Promise((resolve, reject) => {
            this.createSelectorQuery().select('#canvas')
                .fields({ node: true, size: true })
                .exec((res) => {
                    console.log(res, 'canvas？？')
                    if (res[0].node == null) {
                        return
                    }
                    let canvas = res[0].node,
                        ctx = canvas.getContext('2d');

                    canvas.width = width;
                    canvas.height = height;

                    this.canvas = canvas;
                    this.canvasCtx = ctx;
                    resolve(true);
                });
        });
        this.dpr = dpr;
        // this.crmuser = wx.getStorageSync('crmuser');
        console.log(globalData.SystemInfo, 'systimeInfo')
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 关闭弹窗
         */
        cancel() {
            this.setData({
                visible: false,
                mask: false,
            });
        },

        /**
         * 绘制圆角矩形
         */
        roundRect(x, y, w, h, r, color, strokeColor) {
            let ctx = this.canvasCtx;

            ctx.save();
            ctx.beginPath();

            ctx.moveTo(x + r / 2, y);
            ctx.lineTo(x + w - r, y);
            ctx.quadraticCurveTo(x + w, y, x + w, y + r / 2);
            ctx.lineTo(x + w, y + h - r / 2);
            ctx.quadraticCurveTo(x + w, y + h, x + w - r / 2, y + h);
            ctx.lineTo(x + r / 2, y + h);
            ctx.quadraticCurveTo(x, y + h, x, y + h - r / 2);
            ctx.lineTo(x, y + r / 2);
            ctx.quadraticCurveTo(x, y, x + r / 2, y);

            //描边
            if (strokeColor) {
                ctx.lineWidth = 1;
                ctx.strokeStyle = strokeColor;
                ctx.stroke();
            }

            //填充
            if (color) {
                ctx.fillStyle = color;
                ctx.fill();
            }

            ctx.closePath();
            // ctx.clip();
        },

        /**
         * 生成海报
         */
        createPoster() {
            const launchOptions = wx.getLaunchOptionsSync()
            console.log(launchOptions, 'launchOptions')
            if (launchOptions.scene === 1154) {
                return this.setData({
                    'toast.visible': true,
                    'toast.text': '请前往小程序体验完整服务',
                });
            }
            console.log(this.canvasCtx, 'this.canvasCtx')
            if (this.canvasCtx == undefined) {
                this.setData({
                    toast: {
                        visible: true,
                        text: 'PC端或海报环境加载失败，无法生成海报'
                    }
                })
                return
            }
            wx.showLoading({ title: '海报生成中...' });
            this.setData({ sheetVisible: false });

            let { width, height } = this.canvas,
                ctx = this.canvasCtx,
                type = this.data.type,
                bgColor = type === 4 ? '#3D287F' : '#ffffff';
            console.log(type, 'type')
            //清空画布
            ctx.clearRect(0, 0, width, height);

            //背景色
            this.roundRect(0, 0, width, height, 16, bgColor, bgColor);
            ctx.restore();

            switch (type) {
                case 0:
                    this.roundRect(24, 100, 452, 256, 8, '#F4F4F4');
                    ctx.restore();
                    this.drawHospitalInfo();
                    break;
                case 1:
                    this.roundRect(24, 100, 452, 226, 8, '#F4F4F4');
                    ctx.restore();
                    this.drawDoctorInfo();
                    break;
                case 2:
                    this.drawSpuInfo();
                    break;
                case 3:
                    this.drawSpuInfo();
                    break;
                case 4:
                    let fillColor = '';

                    fillColor = ctx.createLinearGradient(30, 178, 572, 688);
                    fillColor.addColorStop(0, 'rgb(70,101,163)');
                    fillColor.addColorStop(1, 'rgb(117,78,164)');

                    this.roundRect(28, 176, 546, 514, 8, fillColor, '#44FFF8');
                    ctx.restore();

                    ctx.beginPath();
                    ctx.lineWidth = .5;
                    ctx.strokeStyle = '#44FFF8';
                    ctx.moveTo(524, 176);
                    ctx.lineTo(574, 226);
                    ctx.closePath();
                    ctx.stroke();

                    ctx.beginPath();
                    ctx.fillStyle = '#3D287F';
                    ctx.moveTo(524, 174);
                    ctx.lineTo(524, 176);
                    ctx.lineTo(574, 226);
                    ctx.lineTo(575, 226);
                    ctx.lineTo(575, 174);
                    ctx.lineTo(524, 174);
                    ctx.fill();
                    ctx.closePath();
                    this.drawAiInfo();
                    break;
                case 5:
                    this.drawSuperMemberInfo();
                    break;
            }
        },

        /**
         * 加载头像
         */
        loadMyAvatar(uri) {
            console.log('进avatar方法', uri)
            let avatar = this.canvas.createImage(),
                type = this.data.type,
                src = uri,
                avatar_w = 80,
                avatar_h = 80,
                ratio = 2,
                x = 24,
                y = 30;

            avatar.src = src;

            return new Promise((resolve, reject) => {
                avatar.onload = () => {
                    resolve({
                        avatar,
                        avatar_w,
                        avatar_h,
                        x,
                        y,
                        ratio
                    });
                }
            });
        },

        /**
         * 加载logo
         */
        loadLogo() {
            console.log('进logo方法')
            let logo = this.canvas.createImage(),
                type = this.data.type,
                src = globalData.imageBaseUri + '/images/tntb_logo.png',
                logo_w = 86,
                logo_h = 86,
                ratio = 2,
                x = 24,
                y = 30;

            logo.src = src;

            return new Promise((resolve, reject) => {
                logo.onload = () => {
                    resolve({
                        logo,
                        logo_w,
                        logo_h,
                        x,
                        y,
                        ratio
                    });
                }
            });
        },

        /**
         * 文字处理换行、省略
         */
        getHandledText(option) {
            let ctx = this.canvasCtx,
                text = option.text,
                tmpArr = [];

            //不换行
            if (!option.wrap) {
                //循环计算字宽，直到不超过指定宽度
                while (ctx.measureText(text).width > option.width) {
                    text = text.slice(0, -1);
                }

                //有被截取的字符，追加省略号
                if (option.text.length !== text.length) text += '...';

                tmpArr.push(text);
            }
            //换行
            else if (option.wrap) {
                let line = 0,
                    text = '';

                for (let i = 0, l = option.text.length; i < l; i++) {
                    let width = ctx.measureText(text + option.text[i]).width;

                    if (width < option.width) {
                        text += option.text[i];
                    } else {
                        tmpArr.push(text);
                        line += 1;
                        text = option.text[i];
                    }

                    if (i === l - 1 && text) {
                        tmpArr.push(text);
                    }
                }
            }

            //超过限制行数省略
            if (option.maxLine && tmpArr.length > option.maxLine) {
                tmpArr.length = option.maxLine;
                tmpArr[option.maxLine - 1] = tmpArr[option.maxLine - 1].slice(0, -1) + '...';
            }

            return tmpArr;
        },

        /**
         * 小程序码
         */
        getMiniCode(option) {
            console.log(option, 'getMiniCode')
            return new Promise((resolve, reject) => {
                let img = option.img;

                delete option.img;

                base.getMiniCode({
                    // spread: 3,
                    // crmuser: this.crmuser,
                    ...option,
                }).then(res => {
                    console.log(res, 'base getMiniCoder res')
                    img.src = res.src;
                    img.onload = function () {
                        resolve(res.info);
                    };
                    console.log(img.src, 'img.src')
                }).catch(err => {
                    reject('获取小程序码信息失败:', err);
                });
            });
        },

        /**
         * 关闭确认授权弹窗
         */
        closeAuthPop() {
            this.setData({
                'modalAuth.show': false,
                visible: false,
            });
        },

        /**
         * 授权
         */
        openSetting() {
            let _this = this;
            wx.openSetting({
                complete(res) {
                    _this.closeAuthPop();
                }
            });
        },

        /**
         * 保存到相册
         */
        saveToAlbum() {
            console.log('是否授权1')
            let cvs = this.canvas,
                _this = this;

            return new Promise(async (resolve, reject) => {
                try {


                    let scope = await utils.wxMethod.getSetting('scope.writePhotosAlbum'), //获取授权信息
                        scopeAlbum = scope.authSetting['scope.writePhotosAlbum']; //是否授权使用相册
                    console.log('是否授权2', scope, 'scope', scopeAlbum, 'scopeAlbum')
                    //用户拒绝授权
                    if (!scopeAlbum && scopeAlbum !== undefined) {
                        wx.hideLoading();
                        _this.setData({ 'modalAuth.show': true });
                        console.log('用户拒绝授权', scope, 'scope', scopeAlbum, 'scopeAlbum')
                    }
                    //已授权或未请求过授权
                    else {
                        console.log('已授权或未请求过授权', scope, 'scope', scopeAlbum, 'scopeAlbum', cvs.width * 750 / wx.getSystemInfoSync().windowWidth)
                        //保存检测图片
                        wx.canvasToTempFilePath({
                            x: 1,
                            y: 1,
                            width: cvs.width,
                            height: cvs.height,
                            destWidth: cvs.width,
                            destHeight: cvs.height,
                            quality: 1,
                            canvas: cvs,
                            async success(res) {
                                //临时路径
                                _this.setData({ tempSrc: res.tempFilePath });

                                wx.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePath,
                                    success(res) {
                                        wx.hideLoading();
                                        resolve(true);
                                    },
                                    fail(err) {
                                        console.log(err);
                                        wx.hideLoading();
                                        reject(`保存海报到相册时失败: ${JSON.stringify(err)}`);
                                        console.log('保存海报到相册时失败', scope, 'scope', scopeAlbum, 'scopeAlbum')
                                    }
                                });
                            },
                            fail(err) {
                                wx.hideLoading();
                                reject(`保存海报时转临时路径失败: ${JSON.stringify(err)}`);
                                console.log('保存海报时转临时路径失败', scope, 'scope', scopeAlbum, 'scopeAlbum')
                            }
                        });
                    }
                } catch (e) {
                    console.log(e);
                    wx.hideLoading();
                    reject(`保存海报到相册时失败1: ${JSON.stringify(e)}`);
                    console.log('保存海报到相册时失败', scope, 'scope', scopeAlbum, 'scopeAlbum')
                }
            });
        },

        /**
         * 关闭弹窗
         */
        async closePop() {
            this.setData({
                visible: false,
                canvasVisible: false,
            });

            await utils.sleep(250);
            this.setData({ tempSrc: '' });
        },

        /**
         * 绘制医院信息
         */
        async drawHospitalInfo() {
            let ctx = this.canvasCtx,
                data = this.data.data,
                logo = this.canvas.createImage(), //医院loog
                star = this.canvas.createImage(), //星星
                strict = this.canvas.createImage(), //严选标签
                code = this.canvas.createImage(); //小程序码

            ctx.textAlign = 'left';
            ctx.lineWidth = 1;
            ctx.textBaseline = 'top';
            logo.src = data.logo; //医院logo
            star.src = globalData.imageBaseUri + '/v2.6.3/star.png'; //医院得分

            // let pro_getInfo = wx.getImageInfo({src: data.logo}),
            let pro_getInfo = this.getImgInfo(data.logo),
                pro_load = new Promise(resolve => {
                    logo.onload = function () {
                        resolve(true);
                    };
                }),
                pro_logo = new Promise((resolve, reject) => { //logo
                    this.loadLogo().then(res => {
                        if (res) {
                            let { logo, logo_w, logo_h, x, y, ratio } = res;
                            ctx.drawImage(logo, 0, 0, logo_w, logo_h, x, y, logo_w / ratio, logo_h / ratio);
                            resolve(true);
                        }
                    }).catch(reject);
                }),
                pro_strict = new Promise((resolve, reject) => {
                    strict.src = globalData.imageBaseUri + '/v2.6.3/ico-strict.png';

                    //严选医院
                    if (data.isDeepContact) {
                        strict.onload = () => {
                            resolve(true);
                        };
                    } else resolve(false);
                }),
                pro_star = new Promise((resolve, reject) => { //医院得分
                    star.onload = function () {
                        let star_str = data.overallRatings,
                            star_num = Math.round(star_str), //得分
                            margin = 5,
                            w = 20;

                        for (let i = 0; i < star_num; i++) {
                            ctx.drawImage(star, 0, 0, 40, 40, 200 + i * (margin + w), 212, w, 20);
                        }

                        ctx.font = '22px PingFangSC-Regular';
                        ctx.fillText(star_str + '', 220 + star_num * (margin + w), 213);
                        resolve(true);
                    };
                }),
                pro_code = new Promise((resolve, reject) => {
                    this.getMiniCode({
                        img: code,
                        dataId: data.id,
                        userId: data.userId,
                        page: `pages/hospital/hospitalDetail/hospitalDetail`
                    }).then(res => {
                        //小程序码
                        res.width && ctx.drawImage(code, 0, 0, res.width, res.height, (this.canvas.width - 142) / 2, 438, 142, 142);
                        resolve(true);
                    }).catch(reject);
                });

            //图片绘制
            Promise.all([pro_getInfo, pro_load, pro_strict, pro_code, pro_star, pro_logo]).then(async res => {
                console.log(res, '图片绘制res')
                let resArr = [...res],
                    info = resArr[0],
                    loaded = resArr[1],
                    loaded_strict = resArr[2];

                //医院logo
                this.roundRect(48, 192, 136, 136, 12);
                loaded && ctx.drawImage(logo, 0, 0, info.width, info.height, 48, 192, 136, 136);
                ctx.restore();
                //严选
                loaded_strict && ctx.drawImage(strict, 0, 0, 272, 68, 48, 297, 136, 34);

                //保存到相册
                await this.saveToAlbum();
                this.setData({ canvasVisible: true });
            }).catch(err => {
                this.setData({
                    visible: false,
                    // 'toast.visible': true,
                    // 'toast.text': '海报保存失败,请重试',
                });
                utils.log.error('海报保存失败', err);
                wx.hideLoading();
            });

            let op_name = {
                text: data.name,
                width: 404,
                wrap: false,
                fontSize: 30,
                fontFamily: 'PingFangSC-Medium',
                x: 48,
                y: 130,
            },
                op_address = {
                    text: data.address,
                    width: 244,
                    wrap: true,
                    fontSize: 24,
                    fontFamily: 'PingFangSC-Regular',
                    x: 200,
                    y: 250,
                    maxLine: 3, //超过3行省略
                };

            //医院名称
            ctx.fillStyle = '#000';
            ctx.font = `${op_name.fontSize}px ${op_name.fontFamily}`;
            this.getHandledText(op_name).map((item, idx) => {
                ctx.fillText(item, op_name.x, op_name.y + idx * op_name.fontSize);
            });

            //医院地址
            ctx.fillStyle = '#484848';
            ctx.font = `${op_address.fontSize}px ${op_address.fontFamily}`;
            this.getHandledText(op_address).map((item, idx) => {
                ctx.fillText(item, op_address.x, op_address.y + idx * (op_address.fontSize + 2));
            });

            ctx.fillStyle = '#000000';
            ctx.textAlign = 'center';
            ctx.fillText('我觉得这家机构很不错，快来看看吧', this.canvas.width / 2, 388);
            ctx.fillStyle = '#666666';
            ctx.font = '22px PingFangSC-Regular';
            ctx.fillText('长按识别小程序码查看详情', this.canvas.width / 2, 598);
        },

        /**
         * 绘制医生信息
         */
        async drawDoctorInfo() {
            let ctx = this.canvasCtx,
                data = this.data.data,
                logo = this.canvas.createImage(), //医生头像
                cer = this.canvas.createImage(), //医生认证
                code = this.canvas.createImage(); //小程序码

            ctx.textAlign = 'left';
            ctx.lineWidth = 1;
            ctx.textBaseline = 'top';
            logo.src = data.headImage; //医生头像

            // let pro_getInfo = wx.getImageInfo({src: data.headImage}),
            let pro_getInfo = this.getImgInfo(data.headImage),
                pro_load = new Promise(resolve => {
                    logo.onload = function () {
                        resolve(true);
                    };
                }),
                pro_cer = new Promise((resolve, reject) => {
                    cer.src = globalData.imageBaseUri + '/v1/certificate-meibei.png';
                    cer.onload = () => {
                        resolve(true);
                    };
                }),
                pro_logo = new Promise((resolve, reject) => { //logo
                    this.loadLogo().then((res) => {
                        if (res) {
                            let { logo, logo_w, logo_h, x, y, ratio } = res;

                            ctx.drawImage(logo, 0, 0, logo_w, logo_h, x, y, logo_w / ratio, logo_h / ratio);
                            resolve(true);
                        }
                    }).catch(reject);
                }),
                pro_code = new Promise((resolve, reject) => { //小程序码
                    this.getMiniCode({
                        img: code,
                        dataId: data.id,
                        userId: data.userId,
                        page: `pages/doctor/doctorDetail/doctorDetail`
                    }).then((res) => {
                        res.width && ctx.drawImage(code, 0, 0, res.width, res.height, (this.canvas.width - 142) / 2, 408, 142, 142);
                        resolve(true);
                    }).catch(reject);
                });

            //图片绘制
            Promise.all([pro_getInfo, pro_load, pro_cer, pro_code, pro_logo]).then(async res => {
                let resArr = [...res],
                    info = resArr[0],
                    loaded = resArr[1],
                    cer_loaded = resArr[2],
                    h_x = 48,
                    h_y = 140,
                    h_w = 144;

                //医生头像
                ctx.save();
                ctx.beginPath();
                ctx.arc(h_x + h_w / 2, h_y + h_w / 2, h_w / 2, 0, Math.PI * 2);
                ctx.closePath();
                ctx.clip();
                loaded && ctx.drawImage(logo, 0, 0, info.width, info.height, h_x, h_y, h_w, h_w);
                ctx.restore();

                cer_loaded && ctx.drawImage(cer, 0, 0, 240, 78, 52, 260, 136, 44.2);

                //保存到相册
                await this.saveToAlbum();
                this.setData({ canvasVisible: true });
            }).catch(err => {
                this.setData({
                    visible: false,
                    'toast.visible': true,
                    'toast.text': '海报保存失败,请重试',
                });
                utils.log.error('海报保存失败', err);
                wx.hideLoading();
            });

            let op_hospital = {
                text: data.hospitalName,
                width: 244,
                wrap: true,
                fontSize: 24,
                fontFamily: 'PingFangSC-Regular',
                x: 208,
                y: 232,
                maxLine: 2,
            };

            ctx.fillStyle = '#000';

            ctx.font = `32px PingFangSC-Semibold`;
            let name_x = 208,
                name_y = 144,
                name_w = ctx.measureText(data.name).width;

            //医生姓名
            ctx.fillText(data.name, name_x, name_y);
            ctx.font = '22px PingFangSC-Regular';

            let job_w = ctx.measureText(data.jobTitle).width,
                job_x = name_x + name_w + 4, //4为间距
                padding = 8; //字与背景的左右padding

            this.roundRect(job_x, name_y + 1, job_w + padding * 2, 30, 4, '#FFDF00');
            ctx.restore();

            ctx.fillStyle = '#000';
            //职级
            ctx.fillText(data.jobTitle, job_x + padding, name_y + 5); //5为医生姓名字号32 减职级字号30 除2的结果
            //从业年限
            ctx.fillText(`从业年${data.year}年`, 211, 194);

            //医生所在医院名称
            ctx.fillStyle = '#B3B3B3';
            ctx.font = `${op_hospital.fontSize}px ${op_hospital.fontFamily}`;
            this.getHandledText(op_hospital).map((item, idx) => {
                ctx.fillText(item, op_hospital.x, op_hospital.y + idx * (op_hospital.fontSize + 2));
            });

            ctx.fillStyle = '#000000';
            ctx.textAlign = 'center';
            ctx.font = '24px PingFangSC-Regular';
            ctx.fillText('我发现了一位很棒的医生，推荐给你', this.canvas.width / 2, 356);
            ctx.fillStyle = '#666666';
            ctx.font = '22px PingFangSC-Regular';
            ctx.fillText('长按识别小程序码查看详情', this.canvas.width / 2, 566);
        },

        /**
         * 绘制spu、sku信息
         */
        async drawSpuInfo() {
            let ctx = this.canvasCtx,
                data = this.data.data,
                type = this.data.type,
                logo = this.canvas.createImage(), // 商品图片
                avatar = this.canvas.createImage(), // 用户头像
                code = this.canvas.createImage(), //小程序码
                page = `pages/product/detail/detail`;
            console.log('进来了 data', data)

            data.img = data.img || globalData.imageBaseUri + '/images/tntb_logo.png';
            data.avatar = data.avatar || globalData.imageBaseUri + '/images/tntb_logo.png';
            console.log(data, (globalData.imageBaseUri + '/images/tntb_logo.png', 'data'))
            ctx.textAlign = 'left';
            ctx.lineWidth = 1;
            ctx.textBaseline = 'top';
            logo.src = data.img; //商品封面
            avatar.src = data.avatar; // 头像

            let pro_getInfo = this.getImgInfo(data.img),
                pro_avatarInfo = this.getImgInfo(data.avatar),
                pro_logo = this.loadLogo(),
                pro_load = new Promise(resolve => {
                    logo.onload = function () {
                        resolve(true);
                    };
                }),
                pro_avatar = new Promise((resolve, reject) => {
                    avatar.onload = () => {
                        resolve(true);
                    };
                }),
                pro_code = this.getMiniCode({
                    contentId: '',
                    contentType: '',
                    title: '',
                    page: page,
                    centerImg: globalData.imageBaseUri + '/images/tntb_logo.png',
                    scene: data.userId + '&' + data.id,
                    width: 120,
                    img: code
                });

            //图片绘制
            Promise.all([pro_getInfo, pro_load, pro_code, pro_logo, pro_avatarInfo, pro_avatar]).then(async res => {
                console.log(res, "图片绘制")
                console.log(logo, 'logo?', code, 'code?', avatar, 'avatar?')
                let resArr = [...res],
                    info = resArr[0],
                    loaded = resArr[1],
                    info_code = resArr[2],
                    logo_loaded = resArr[3],
                    avatarInfo = resArr[4],
                    avatar_loaded = resArr[5];
                //logo
                if (logo_loaded) {
                    console.log(logo_loaded, '这是啥')
                    // let { logo, logo_w, logo_h, x, y, ratio } = logo_loaded;
                    // ctx.drawImage(logo, 0, 0, logo_w, logo_h, x, y, logo_w / ratio, logo_h / ratio);
                }
                //封面
                let dis_w = 452,
                    dis_h = 300,
                    cut_h = info.width * dis_h / dis_w;

                loaded && ctx.drawImage(logo, 0, 0, info.width, cut_h, 24, 104, dis_w, dis_h);

                //小程序码
                info_code.width && ctx.drawImage(code, 0, 0, info_code.width, info_code.height, 338, 438, 138, 138);
                console.log(code, '是否达到保存步骤')
                console.log(logo, '是否达到保存步骤1')
                console.log(avatar, '是否达到保存步骤2')

                // 头像
                let a_w = 452,
                    a_h = 300,
                    acut_h = avatarInfo.width * a_h / a_w;
                avatar_loaded && ctx.drawImage(avatar, 24, 24, 80, 80);
                ctx.restore();

                let op_name = {
                    text: data.name,
                    width: 292,
                    wrap: true,
                    fontSize: 26,
                    fontFamily: 'PingFangSC-Medium',
                    x: 24,
                    y: 430,
                    maxLine: 2,
                    fontWeight: 600
                };

                let op_nickname = {
                    text: data.userName,
                    width: 292,
                    wrap: true,
                    fontSize: 26,
                    fontFamily: 'PingFangSC-Medium',
                    x: 114,
                    y: 54,
                    maxLine: 1,
                    fontWeight: 600
                }

                // 商品名称
                let calcY = 435

                ctx.fillStyle = '#000';
                ctx.font = `${op_name.fontSize}px ${op_name.fontFamily}`;
                this.getHandledText(op_name).forEach((item, idx) => {
                    calcY += idx * (op_name.fontSize + 4)
                    ctx.fillText(item, op_name.x, calcY)
                });

                console.log(calcY, 'calcy')

                // 用户昵称
                ctx.fillStyle = '#000';
                ctx.font = `${op_nickname.fontSize}px ${op_nickname.fontFamily}`;
                this.getHandledText(op_nickname).forEach((item, idx) => {
                    ctx.fillText(item, op_nickname.x, op_nickname.y)
                });

                //价格
                ctx.font = '24px PingFangSC-Regular';
                ctx.fillStyle = '#E78140';
                ctx.fillText(data.isGroup ? '3人团 ¥' : '¥', 24, 588);
                ctx.font = '34px PingFangSC-Semibold';

                //spu
                if (this.data.type === 2) {
                    let text = data.minPrice + '-' + data.maxPrice;

                    if (!data.minPrice && !data.maxPrice) text = '面诊后确认';

                    ctx.fillText(text, 46, 580, 176);
                }

                //sku
                if (this.data.type === 3) {
                    console.log(data, 'canvas data')
                    let price = data.minPrice
                    let min_w = ctx.measureText(price).width,
                        min_x = 46,
                        min_y = 580,
                        show_min_x = min_x + min_w + 28,
                        show_min_y = 580 + 10; //34 - 24

                    console.log('ctx.measureText(price)', ctx.measureText(price))

                    ctx.fillText(price, min_x, min_y, 100);
                    ctx.font = '22px PingFangSC-Regular';
                    // if (data.isGroup) {
                    //     data.disGroupRise && ctx.fillText('起', min_x + min_w, show_min_y, 30);
                    // } else {
                    //     data.disMinRise && ctx.fillText('起', min_x + min_w, show_min_y, 30);
                    // }

                    //原价与售价相等时不展示原价 商品类型为实物时也不展示原价 从会员商城进来的也不显示原价 
                    // !data.fromvip && data.productType == 0 && data.minPrice !== data.showMinPrice
                    // 拼团不显示原价
                    // if (!data.isGroup) {
                    ctx.fillStyle = '#AAAAAA';

                    let show_min = '¥' + data.showMinPrice,
                        show_min_w = ctx.measureText(show_min).width,
                        maxWidth = 66;

                    ctx.fillText(show_min, show_min_x, show_min_y, maxWidth);
                    // ctx.strokeStyle = '#AAAAAA';
                    // ctx.lineWidth = 2;
                    ctx.moveTo(show_min_x, show_min_y + 11); //
                    ctx.lineTo(show_min_x + (show_min_w > maxWidth ? maxWidth : show_min_w), show_min_y + 11);
                    ctx.stroke();
                    // }
                }

                ctx.fillStyle = '#666666';
                ctx.font = '22px PingFangSC-Regular';
                ctx.textAlign = 'right';
                ctx.fillText('识别小程序码查看详情', 470, 592);

                //保存到相册
                await this.saveToAlbum();
                this.setData({ canvasVisible: true });
            }).catch(err => {
                this.setData({
                    visible: false,
                    'toast.visible': true,
                    'toast.text': err,
                });
                utils.log.error('sku海报保存失败', err);
                wx.hideLoading();
            });


        },

        /**
         * 绘制AI信息
         */
        async drawAiInfo() {
            let ctx = this.canvasCtx,
                data = this.data.data,
                bg = this.canvas.createImage(), //背景
                avatar = this.canvas.createImage(), //分享图
                sex = this.canvas.createImage(), //性别
                bg_sex = this.canvas.createImage(), //性别背景
                bg_age = this.canvas.createImage(), //年龄背景
                bg_skin = this.canvas.createImage(), //皮肤背景
                bg_beauty = this.canvas.createImage(), //颜值背景
                star = this.canvas.createImage(), //星星
                code = this.canvas.createImage(); //小程序码

            ctx.textAlign = 'left';
            ctx.lineWidth = 1;
            ctx.textBaseline = 'top';
            avatar.src = data.img; //分享图

            let pro_logo = new Promise((resolve, reject) => { //logo
                this.loadLogo().then(res => {
                    if (res) {
                        let { logo, logo_w, logo_h, x, y, ratio } = res;
                        ctx.drawImage(logo, 0, 0, logo_w, logo_h, x, y, logo_w / ratio, logo_h / ratio);
                        resolve(true);
                    }
                }).catch(reject);
            }),
                pro_star = new Promise((resolve, reject) => {
                    star.src = globalData.imageBaseUri + '/v2.6.3/triangle.png';
                    star.onload = () => {
                        ctx.drawImage(star, 0, 0, 72, 74, 540, 173, 36, 37);
                        resolve(true);
                    };
                }),
                pro_code = new Promise((resolve, reject) => { //小程序码
                    this.getMiniCode({
                        img: code,
                        dataId: data.id,
                        check_time: data.check_time,
                        userId: data.userId,
                        stage: data.stage,
                        from: data.from,
                        page: `sub_third/pages/AI/face/face`,
                    }).then(res => {
                        if (res.width) {
                            ctx.fillStyle = '#ffffff';
                            ctx.beginPath();
                            ctx.arc(98, 788, 74, 0, Math.PI * 2);
                            ctx.fill();
                            ctx.drawImage(code, 0, 0, res.width, res.height, 30, 720, 136, 136);
                            resolve(true);
                        }
                    }).catch(reject);
                }),
                // pro_info = wx.getImageInfo({src: data.img}),
                pro_info = this.getImgInfo(data.img),
                pro_avatar = new Promise((resolve, reject) => {
                    avatar.onload = () => {
                        resolve(true);
                    };
                }),
                pro_sex = new Promise((resolve, reject) => {
                    sex.src = globalData.imageBaseUri + (data.gender === 'Female' ? '/v2.6.2/female.png' : '/v2.6.2/male.png');
                    sex.onload = () => {
                        ctx.drawImage(sex, 0, 0, 87, 87, 84, 571, 48, 48);
                        resolve(true);
                    };
                }),
                pro_bg_sex = new Promise((resolve, reject) => {
                    bg_sex.src = globalData.imageBaseUri + '/v2.6.2/ico-gender.png';
                    bg_sex.onload = () => {
                        ctx.drawImage(bg_sex, 0, 0, 201, 201, 53, 555, 108, 108);
                        resolve(true);
                    };
                }),
                pro_bg_age = new Promise((resolve, reject) => {
                    bg_age.src = globalData.imageBaseUri + '/v2.6.2/bg-age.png';
                    bg_age.onload = () => {
                        ctx.drawImage(bg_age, 0, 0, 201, 201, 181, 555, 108, 108);
                        ctx.font = '45px Akrobat-Black';
                        ctx.textAlign = 'center';
                        ctx.fillStyle = '#ffffff';
                        ctx.fillText(data.age, 235, 571, 108);
                        resolve(true);
                    };
                }),
                pro_bg_skin = new Promise((resolve, reject) => {
                    bg_skin.src = globalData.imageBaseUri + '/v2.6.2/bg-skin.png';
                    bg_skin.onload = () => {
                        ctx.drawImage(bg_skin, 0, 0, 201, 201, 309, 555, 108, 108);
                        ctx.font = '35px PingFangSC-Semibold';
                        ctx.textAlign = 'center';
                        ctx.fillStyle = '#ffffff';
                        ctx.fillText(data.skinstatus, 364, 571, 108);
                        resolve(true);
                    };
                }),
                pro_bg_beauty = new Promise((resolve, reject) => {
                    bg_beauty.src = globalData.imageBaseUri + '/v2.6.2/ico-beauty.png';
                    bg_beauty.onload = () => {
                        ctx.drawImage(bg_beauty, 0, 0, 201, 201, 438, 555, 108, 108);
                        ctx.font = '45px Akrobat-Black';
                        ctx.textAlign = 'center';
                        ctx.fillStyle = '#ffffff';
                        ctx.fillText(data.beauty, 492, 571, 108);
                        resolve(true);
                    };
                }),
                pro_bg = new Promise((resolve, reject) => {
                    bg.src = globalData.imageBaseUri + '/v2.6.3/share-bg.png';
                    bg.onload = () => {
                        let width = 936,
                            height = 316;

                        ctx.drawImage(bg, 0, 0, width, height, 66, 738, width / 2, height / 2);
                        resolve(true);
                    }
                });

            //图片绘制
            Promise.all([pro_info, pro_avatar, pro_code, pro_logo, pro_bg, pro_sex, pro_bg_sex, pro_bg_age, pro_bg_skin, pro_bg_beauty, pro_star]).then(async res => {
                let resArr = [...res],
                    info_avatar = resArr[0],
                    avatar_loaded = resArr[1];


                //分享图
                if (avatar_loaded) {
                    let sx = 53,
                        sy = 314,
                        bw = 2,
                        br = 3;

                    this.roundRect(sx - bw, sy - bw, 160 + 2 * bw, 160 + 2 * bw, br, '', '#49FEF8');
                    ctx.drawImage(avatar, 0, 0, info_avatar.width, info_avatar.height, sx, sy, 160, 160);
                    ctx.restore();
                }

                //保存到相册
                await this.saveToAlbum();
                this.setData({ canvasVisible: true });
            }).catch(err => {
                this.setData({
                    visible: false,
                    'toast.visible': true,
                    'toast.text': '海报保存失败,请重试',
                });
                utils.log.error('海报保存失败', err);
                wx.hideLoading();
            });

            //奇葩需求,可能造成莫名其妙的文案，主要看数字研究院接口返回
            data.desc = '经AI检测，' + data.desc.replace(/你/g, '我');

            let op_share = {
                text: data.shareText,
                width: 480,
                wrap: true,
                fontSize: 32,
                fontFamily: 'PingFangSC-Medium',
                x: 53,
                y: 208,
                maxLine: 2,
            },
                op_desc = {
                    text: data.desc,
                    width: 318,
                    wrap: true,
                    fontSize: 22,
                    fontFamily: 'PingFangSC-Regular',
                    x: 229,
                    y: 314,
                    maxLine: 5,
                };

            ctx.fillStyle = '#44FFF8';
            ctx.font = `${op_share.fontSize}px ${op_share.fontFamily}`;
            this.getHandledText(op_share).map((item, idx) => ctx.fillText(item, op_share.x, op_share.y + idx * (op_share.fontSize + 4)));

            ctx.font = `${op_desc.fontSize}px ${op_desc.fontFamily}`;
            this.getHandledText(op_desc).map((item, idx) => ctx.fillText(item, op_desc.x, op_desc.y + idx * (op_desc.fontSize + 4)));

            ctx.beginPath();
            ctx.moveTo(30, 152);
            ctx.lineTo(560, 152);
            ctx.stroke();
            ctx.arc(35, 152, 5, 0, Math.PI * 2);
            ctx.arc(565, 152, 5, 0, Math.PI * 2);
            ctx.fill();
            ctx.closePath();

            ctx.textAlign = 'left';
            ctx.font = '26px PingFangSC-Medium';
            ctx.fillText('如果觉得有趣，你也来测测吧~', 202, 755);
            ctx.font = '22px PingFangSC-Regular';
            ctx.fillText('识别小程序码查看详情', 202, 798);
        },

        /**
         * 绘制超级会员海报
         */
        async drawSuperMemberInfo() {
            try {
                let fontWidth;
                const ctx = this.canvasCtx
                const data = this.data.data

                const miniCodeIMG = this.canvas.createImage()

                const [, logo] = await Promise.all([
                    this.getMiniCode({ img: miniCodeIMG, dataId: this.data.data, userId: globalData.userInfo.userId, page: 'pages/member/index/index', }),
                    this.loadLogo()
                ])
                const logoImg = logo.logo

                ctx.drawImage(logoImg, 24, 31, 120, 43);

                ctx.fillStyle = '#000000';
                ctx.textAlign = 'center';
                ctx.font = '34px PingFangSC-Medium';
                // ctx.fillText('美呗超级会员', this.canvas.width / 2, 113);
                ctx.fillText('99元/年', this.canvas.width / 2, 163);
                ctx.font = '24px PingFangSC-Medium';
                ctx.fillText('自用省钱，分享赚钱', this.canvas.width / 2, 620);
                // ctx.fillText('开通美呗超级会员', this.canvas.width / 2, 655)
                ctx.fillText('立领价值188元会员礼', this.canvas.width / 2, 690);
                ctx.fillText('会员商城消费，全场低至5折起 ', this.canvas.width / 2, 725);

                ctx.drawImage(miniCodeIMG, 229, 760, 142, 142);
                ctx.fillStyle = '#666666';
                ctx.font = '22px PingFangSC-Regular';
                ctx.fillText('识别小程序码查看详情 ', this.canvas.width / 2, 940);

                this.roundRect(24, 210, 552, 345, 8, '#f4ebe1')

                // right 商品
                const renderRight = async (product, leftOffset, topOffset) => {
                    const image = await this.getImage(product.image)
                    // this.roundRect(333, 256, 216, 259, 8, '#fff', '#ccc')
                    this.roundRect(leftOffset, topOffset, 216, 259, 8, '#fff', '#ccc')
                    ctx.textAlign = 'left';
                    ctx.fillStyle = '#E78140';
                    ctx.font = '15px PingFangSC-Medium';
                    ctx.fillText('￥', leftOffset + 19, topOffset + 182);
                    ctx.font = '23px PingFangSC-Medium';
                    ctx.fillText(product.price, leftOffset + 32, topOffset + 181);
                    fontWidth = ctx.measureText(product.price).width
                    ctx.fillStyle = '#B3B3B3';
                    ctx.font = '15px PingFangSC-Medium';
                    ctx.fillText('起', leftOffset + 32 + fontWidth + 5, topOffset + 189);
                    ctx.fillStyle = '#000000';
                    this.getHandledText({
                        text: product.name,
                        width: 191,
                        wrap: true,
                        maxLine: 2,
                        fontSize: 16,
                        fontFamily: 'PingFangSC-Regular',
                        x: leftOffset + 19,
                        y: topOffset + 208,
                    }).forEach((text, idx) => {
                        ctx.fillText(text, leftOffset + 19, topOffset + 208 + idx * 20);
                    });
                    ctx.drawImage(image, 0, 0, image.width, (139 / 191) * image.width, leftOffset + 13, topOffset + 13, 191, 139);
                }

                // center 商品
                const renderCenter = async (product, leftOffset, topOffset) => {
                    const image = await this.getImage(product.image)

                    this.roundRect(leftOffset, topOffset, 240, 288, 8, '#fff', '#ccc')
                    ctx.textAlign = 'left';
                    ctx.fillStyle = '#E78140';
                    ctx.font = '17px PingFangSC-Medium';
                    ctx.fillText('￥', leftOffset + 14, topOffset + 202);
                    ctx.font = '25px PingFangSC-Medium';
                    ctx.fillText(product.price, leftOffset + 32, topOffset + 202);
                    fontWidth = ctx.measureText(product.price).width
                    ctx.fillStyle = '#B3B3B3';
                    ctx.font = '17px PingFangSC-Medium';
                    ctx.fillText('起', leftOffset + 37 + fontWidth, topOffset + 202);
                    ctx.fillStyle = '#000000';
                    this.getHandledText({
                        text: product.name,
                        width: 212,
                        wrap: true,
                        maxLine: 2,
                        fontSize: 25,
                        fontFamily: 'PingFangSC-Regular',
                        x: leftOffset + 14,
                        y: topOffset + 230,
                    }).forEach((text, idx) => {
                        ctx.fillText(text, leftOffset + 14, topOffset + 230 + idx * 25);
                    });
                    ctx.drawImage(image, 0, 0, image.width, (154 / 212) * image.width, leftOffset + 14, topOffset + 14, 212, 154);
                }

                switch (data.length) {
                    case 0:
                        // 渲染默认商品
                        await renderCenter({
                            price: 99,
                            name: '绽妍皮肤修护敷料6片/盒  蓝色院线同款舒缓保湿修护',
                            image: this.data.imageBaseUri + '/v2.6.6/default-product-3.png'
                        }, 188, 238)
                        break
                    case 1:
                        await renderCenter(data[0], 188, 238)
                        break
                    case 2:
                        await Promise.all([
                            renderCenter(data[0], 51, 238),
                            renderCenter(data[1], 313, 238)
                        ])
                        break
                    case 3:
                        await Promise.all([
                            renderRight(data[0], 50, 250),
                            renderRight(data[2], 333, 250)
                        ])

                        await renderCenter(data[1], 188, 238)
                        break
                }

                await this.saveToAlbum();
                wx.hideLoading();
                this.setData({ canvasVisible: true });
            } catch (e) {
                utils.log.error('超级会员海报保存失败', e);
                this.setData({
                    visible: false,
                    'toast.visible': true,
                    'toast.text': '海报保存失败,请重试',
                });
                wx.hideLoading();
            }

        },

        getImage(src) {
            return new Promise((resolve, reject) => {
                const img = this.canvas.createImage()
                this.getImgInfo(src)
                    .then(info => {
                        img.src = info.path
                        img.onload = () => resolve(img)
                        img.onerror = reject
                    })
                    .catch(reject)
            })

        },

        // 获取图片本地地址，真机才会显示
        getImgInfo(src) {
            console.log('src', src)

            return new Promise((resolve, reject) => {
                wx.getImageInfo({
                    src: src,
                    success(res) {
                        console.log('getImgInfo', res)
                        resolve(res)
                    },
                    fail(res) {
                        reject(res);
                        console.log('获取图片信息失败', src, res);
                    }
                })
            })
        },

    }
})
